package com.Algorithm.HUAWEI.three20220323;

import com.sun.org.apache.xalan.internal.xsltc.trax.XSLTCSource;

import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: zjz
 * @Date: 2022/04/15/14:46
 * @Description:
 * @Target:
 */
public class 表达式求值 {


    public static void main(String[] args) {
        System.out.println(count("6*(1+5)"));
    }
    // 对于正常公式计算，进来一个数组，它的下标移动是共享的
    static int index;
    static int count(String ss){
        int sum = 0;  // 求和
        Stack<Integer> integers = new Stack<>();  // 放入数
        char opt = '+';  // 加减乘除运算。默认加
        int num = 0;  // 数字，正常可能不是一位数
        while (index<ss.length()){
            if (index<ss.length()&&ss.charAt(index)=='('){
                index++;
                num = count(ss);

            }


            while (index<ss.length()&&ss.charAt(index)>='0'&&ss.charAt(index)<='9'){
                num = num*10+(ss.charAt(index)-'0');
                index++;
            }

            switch (opt){
                case '+':integers.push(num);break;
                case '-':integers.push(-num);break;
                case '*':integers.push(integers.pop()*num);break;
                case '/':integers.push(integers.pop()/num);break;
            }

            num =  0;


            if (index<ss.length()){
                opt = ss.charAt(index);
                if (ss.charAt(index)==')'){
                    index++;
                    break;
                }
            }

            index++;
        }



        while (!integers.empty()){
            sum += integers.pop();
        }
        return sum;
    }
}
